package config

import (
	"gitee.com/kaylee595/gkaylee/kerr"
	"gitee.com/kaylee595/wuaipojieCheck/internal/service"
	"gitee.com/kaylee595/wuaipojieCheck/pkg/wuaipojie"
	"gitee.com/kaylee595/yesCaptcha"
	"github.com/imroc/req/v3"
	"github.com/spf13/viper"
	"go.nhat.io/cookiejar"
	"golang.org/x/net/publicsuffix"
	"net/http"
)

type Config struct {
	Username       string
	Password       string
	YesCaptchaKey  string
	UserAgent      string
	CookieFilename string
	DumpHTTP       bool
}

func (c *Config) NewCookieJar() http.CookieJar {
	return cookiejar.NewPersistentJar(
		cookiejar.WithFilePath(c.CookieFilename),
		cookiejar.WithFilePerm(0600),
		cookiejar.WithPublicSuffixList(publicsuffix.List),
	)
}

// NewHTTPClient if jar is nil, will use standard library cookiejar.
func (c *Config) NewHTTPClient(jar http.CookieJar) *req.Client {
	httpClient := req.C().SetTLSFingerprintEdge().ImpersonateChrome()
	httpClient.SetUserAgent(c.UserAgent)
	if jar != nil {
		httpClient.SetCookieJar(jar)
	}
	if c.DumpHTTP {
		httpClient.EnableDumpAllToFile("logs/dumpHTTP.log")
	}
	return httpClient
}

// NewYesCaptcha if httpClient is nil, will use req.C() created client.
func (c *Config) NewYesCaptcha(httpClient *req.Client) *yesCaptcha.Client {
	options := []yesCaptcha.Options{
		yesCaptcha.WithSoftId(61751),
	}
	if httpClient != nil {
		options = append(options, yesCaptcha.WithHttpClient(httpClient))
	}
	return yesCaptcha.NewClient(c.YesCaptchaKey, options...)
}

func (c *Config) NewChecker(wa *wuaipojie.Client, yc *yesCaptcha.Client) *service.Checker {
	return &service.Checker{
		Wuai:         wa,
		YesCaptcha:   yc,
		WuaiUsername: c.Username,
		WuaiPassword: c.Password,
	}
}

var Instance Config

func Load(filename ...string) (Config, error) {
	ret := new(Config)
	if len(filename) > 0 && filename[0] != "" {
		viper.SetConfigFile(filename[0])
	} else {
		viper.AddConfigPath(".")
		viper.SetConfigName("config")
		viper.SetConfigType("yaml")
	}
	{
		viper.SetDefault("userAgent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36 Edg/133.0.0.0")
		viper.SetDefault("cookieFilename", "wuaiCookie.json")
	}
	err := viper.ReadInConfig()
	if err != nil {
		return *ret, kerr.WrapTraceStack(err)
	}
	err = viper.Unmarshal(ret)
	if err != nil {
		return *ret, kerr.WrapTraceStack(err)
	}
	return *ret, nil
}
